/*
 * logger.cpp
 *
 *  Created on: Oct 28, 2010
 *      Author: Alexey Brodkin
 */


#include "QSimpleLogger.h"
#include <QTextStream>
#include <QDateTime>
#include <QFile>
#include <QDebug>
#include <qglobal.h>
#include <iostream>



static QTextStream * log_stream;
static QFile * log_file;



static const char* message_type[] =
{
    "(II) " __TIME__ " ",    // Info
    "(WW) " __TIME__ " ",    // Warning
    "(EE) " __TIME__ " ",    // Error
    "(FF) " __TIME__ " "     // Fatal error
};



void custom_message_handler(QtMsgType type, const char* msg)
{
    std::cout << message_type[type] << msg << std::endl;

    if(log_stream && log_stream->device()) {
        *log_stream << message_type[type] << msg << endl;
    }
}



void QSimpleLoggerInstall(QString app_name, QString app_version, bool write_file, QString filename)
{
    qInstallMsgHandler(custom_message_handler);
    if (write_file) {
        log_file = new QFile(filename);

        if(log_file->open(QFile::WriteOnly | QIODevice::Append | QIODevice::Unbuffered))
            log_stream = new QTextStream(log_file);
        else {
            qDebug() << "Unable to open log file " + QString(filename);
        }
    }

    qDebug() << QString("==========================================");
    qDebug() << app_name + QString(" version ") + app_version;
    qDebug() << QString("==========================================");
    qDebug() << "Built on " __DATE__ " at " __TIME__;
    qDebug() << "Based on Qt " + QString(QT_VERSION_STR);
    qDebug() << QString("Markers: (II) informational, (WW) warning,");
    qDebug() << QString("(EE) error, (FF) fatal error.");
    qDebug() << QString("Runned at %1.").arg(QDateTime::currentDateTime().toString());
}



void QSimpleLoggerUninstall()
{
    if (log_stream) {
        qDebug("Log file closed.");
        delete log_stream;
        log_stream = 0;
        delete log_file;
        log_file = 0;
    }

    qInstallMsgHandler(0);
}
